﻿package com.dykj.platform.iadapter.tags;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.struts2.components.Component;

import com.dykj.platform.iadapter.common.Constants;
import com.dykj.platform.iadapter.utils.StringUtils;
import com.opensymphony.xwork2.util.ValueStack;

public class Select extends Component {
	private String name;

	private String value;

	private String editable;

	private String path;

	private String webpath;

	private String model;

	@Override
	public boolean start(Writer arg0) {
		boolean result = super.start(arg0);
		StringBuffer str = new StringBuffer();
		Map select = new HashMap();
		try {
			if (path.startsWith("%{") && path.endsWith("}")) {
				path = path.substring(2, path.length() - 1);
				Object obj = this.getStack().findValue(path);
				if (obj instanceof Map) {
					select = (Map) obj;
				}
			} else {
				select = this.jsToMap(path,webpath);
			}

			if (value != null) {
				if (value.startsWith("%{") && value.endsWith("}")) {
					value = value.substring(2, value.length() - 1);
					value = StringUtils.objToStr(this.getStack().findValue(value));
				}
			} else {
				value = StringUtils.objToStr(this.getStack().findValue(name));
			}
			if (value == null || value.equals("null"))
				value = "";
			if (editable != null) {
				if (editable.startsWith("%{") && editable.endsWith("}")) {
					editable = editable.substring(2, editable.length() - 1);
					editable = StringUtils.objToStr(this.getStack().findValue(
							editable));
				}
			} else {
				editable = StringUtils.objToStr(this.getStack().findValue(
						"requestMsg['editable']"));
			}
			if (editable == null)
				editable = "true";
			/**
			 * 生成表单======================================================
			 */
			if (name.lastIndexOf(".") > 0 && model.equals("true")) {
				name = name.substring(name.lastIndexOf(".") + 1);
			}
			if (editable.equals("false")) {
				str.append("<label>");
				Iterator it = select.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry entry = (Map.Entry) it.next();
					if (!value.equals("") && value.equals(entry.getKey())) {
						str.append(entry.getValue());
						break;
					}
				}
				str.append("</label>");
			} else {
				str.append("<select name='");
				str.append(name);
				str.append("' id='");
				str.append(name);
				str.append("'>");
				Iterator it = select.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry entry = (Map.Entry) it.next();
					String v = entry.getKey().toString();
					str.append("<option value='");
					str.append(v);
					str.append("'");
					if (v.equals(value)) {
						str.append("selected='selected'");
					}
					str.append(">");
					str.append(entry.getValue());
					str.append("</option>");
				}
				str.append("</select>");
			}
			arg0.write(str.toString());
		} catch (IOException e) {
			Logger.getLogger(Input.class.getName()).log(Level.SEVERE, null, e);
		}
		return result;
	}

	private Map jsToMap(String jspath,String path) {
		// Map<String, String> map = new HashMap<String, String>();
		// 使用LinkedHashMap可以决定迭代的顺序。
		Map<String, String> map = new LinkedHashMap<String, String>();
		StringBuffer jsFile = new StringBuffer();
		String js;
		String record = null;
		/**
		 * EBG 初始化JS的全路径 ================================================
		 */
		try {
			StringBuffer filepath;
			//判断操作系统
			String osname=System.getProperties().getProperty("os.name");
			if(osname.startsWith("Windows")){
				filepath = new StringBuffer(path.substring(0,path.length() - 1));
			}else{
				filepath = new StringBuffer(path);
			}
			if (jspath.startsWith(Constants.JS_PATH_SEPARATOR)) {
				String pathArray[] = jspath.split(Constants.JS_PATH_SEPARATOR);
				for (int i = 0; i < pathArray.length; i++) {
					if (pathArray[i].trim() != null
							&& !"".equals(pathArray[i].trim())) {
						filepath.append("\\");
						filepath.append(pathArray[i].trim());
					}
				}
			} else {
				filepath.append(Constants.JS_PATH);
				filepath.append(jspath);
			}
			if (!jspath.endsWith(".js")) {
				filepath.append(".js");
			}
			/**
			 * END
			 * 初始化JS的全路径======================================================
			 */
			/**
			 * 开始读文件======================================================
			 */
			File file = new File(filepath.toString());
			InputStreamReader fr = new InputStreamReader(new FileInputStream(
					file), "UTF-8");
			BufferedReader br = new BufferedReader(fr);
			while ((record = br.readLine()) != null) {
				if (!record.equals("")) {
					jsFile.append(record.trim());
				}
			}
			br.close();
			fr.close();
			js = jsFile.toString();
			js = js.substring(js.indexOf("{") + 1, js.indexOf("}"));
			String jsArray[] = js.split(",");
			/**
			 * 读文件结束======================================================
			 */

			for (int j = 0; j < jsArray.length; j++) {
				String item[] = jsArray[j].split(":");
				String key = StringUtils.objToStr(item[0].subSequence(1, item[0]
						.length() - 1));
				String val = StringUtils.objToStr(item[1].subSequence(1, item[1]
						.length() - 1));
				map.put(key, val);
			}
		} catch (IOException e) {
			Logger.getLogger(Input.class.getName()).log(Level.SEVERE, null, e);
		}
		return map;
	}

	public String getEditable() {
		return editable;
	}

	public void setEditable(String editable) {
		this.editable = editable;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getWebpath() {
		return webpath;
	}

	public void setWebpath(String webpath) {
		this.webpath = webpath;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public Select(ValueStack arg0) {
		super(arg0);
	}
}
